import moment from "moment";
import 'moment/locale/zh-cn';
import React, {useState} from "react";
import Modal from "antd/lib/modal";
import Form from "antd/lib/form";
import DatePicker from "antd/lib/date-picker";
import { wrap as wrapDialog, DialogPropType } from "@/components/DialogWrapper";
import DynamicComponent from "@/components/DynamicComponent";
import {UserProfile} from "@/components/proptypes";
import notification from "@/services/notification";
import OrgStruct from "@/services/orgstruct";
import locale from 'antd/es/date-picker/locale/zh_CN';

function CreateOrgStructDialog({ orgstruct_enum, dialog }) {
  const [effect, setEffect] = useState(moment());
  const [saveInProgress, setSaveInProgress] = useState(false);
  const isCreateOrgStructEnabled = useState(true);//policy.isAdmin() || policy.isDefault();

  function handleEffectChange(date, dateString) {
    setEffect(date);
  }

  function handleSubmit() {
    setSaveInProgress(true);

    OrgStruct.create(orgstruct_enum, {effect_date: effect.format("YYYY-MM-DD")})
    .then(() => {
      dialog.close({ success: true});
    })
    .catch(error => {
      notification.error(error.message, error.detailedMessage);
      setSaveInProgress(false);
    });
  }

  return (
    <Modal
      {...dialog.props}
      {...(isCreateOrgStructEnabled ? {} : { footer: null })}
      title="新建版本"
      okText="保存"
      cancelText="取消"
      okButtonProps={{
        disabled: saveInProgress,
        loading: saveInProgress,
        "data-test": "DashboardSaveButton",
      }}
      cancelButtonProps={{
        disabled: saveInProgress,
      }}
      onOk={handleSubmit}
      closable={!saveInProgress}
      maskClosable={!saveInProgress}
      wrapProps={{
        "data-test": "CreateDashboardDialog",
      }}>
      <DynamicComponent name="CreateOrgStructDialogExtra" disabled={!isCreateOrgStructEnabled}>
      <Form>
        <Form.Item style={{ marginBottom: 5 }} label="生效日期">
        <DatePicker
          locale={locale}
          defaultValue={effect}
          onChange={handleEffectChange}
          placeholder="生效日期"
          disabled={saveInProgress}
          autoFocus
        />
        </Form.Item>
      </Form>
      </DynamicComponent>
    </Modal>
  );
}

CreateOrgStructDialog.propTypes = {
  orgstruct_enum: UserProfile.isRequired,
  dialog: DialogPropType.isRequired,
};

export default wrapDialog(CreateOrgStructDialog);
